
# -*- coding: utf-8 -*-
import json
import logging
import string
import random

from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from apps.baselogic.handlers.product import BaseHandler as ProductHandler
from lib.common import AbstractHandler
from lib.wxpay.wxpay import mch_pay
from services.datamodel.order.models import mm_Order

wechat_logger = logging.getLogger("wechat")


class Handler(ProductHandler):

    def __init__(self, logger):
        AbstractHandler.__init__(self, logger)
        self.METHOD_TAB = {
            'POST': {
                'proxypay': self.proxy_payment,
                'normalpay': self.materials_payment,
                'test_mchpay': self.test_btoc_pay
            },
        }

    @csrf_exempt
    def materials_payment(self, request):
        self.checkMandatoryParams(request, ["paytype", "goods_type", "goods_id"])
        self.is_int_params(request, ["paytype", "goods_type", "goods_id"])
        paytype = int(request.POST['paytype'])
        self.param_in_options(request, 'payfrom', [str(self.PURCHASE_FROM_APP), str(self.PURCHASE_FROM_WEB)])
        payfrom = request.POST.get('payfrom', str(self.PURCHASE_FROM_APP))
        mweb = request.POST.get('mweb', '2')
        if paytype not in (1, 2, 3):  # 1支付宝，2微信, 3苹果
            return JsonResponse({'retcode': 1, 'msg': '参数paytype错误'})
        if payfrom == self.PURCHASE_FROM_WEB and mweb not in ('1', '2', '0'):  # 1手机web端，2为微信浏览器, 0为pc页面
            return JsonResponse({'retcode': 1, 'msg': '参数mweb错误'})

        buyer_type = request.POST.get('buyer_type', 'student')
        if buyer_type and buyer_type not in ('student', 'qrcode'):
            return JsonResponse({'retcode': 1, 'msg': '参数buyer_type错误'})
        client_ip = self.get_client_ip(request)
        if payfrom == self.PURCHASE_FROM_WEB and mweb == '2':
            self.checkMandatoryParams(request, ['openid'])
        openid = request.POST.get('openid')
        share_code = request.POST.get("share_code", None)
        studentid = request.session.get('studentid', 1)
        goods_type = int(request.POST.get("goods_type"))
        goods_id = int(request.POST.get("goods_id"))
        # 直播订单参数接受
        sku_id = int(request.POST.get("sku", 0))
        address = int(request.POST.get("address", 0))
        live_id = int(request.POST.get("live_id", 0))

        return JsonResponse(self.product_purchase(
            studentid, goods_type, goods_id, paytype, int(payfrom), buyer_type, client_ip,
            int(mweb), openid, buyer_user=request.user, share_code=share_code, sku_id=sku_id, address=address,
            live_id=live_id))

    @csrf_exempt
    def proxy_payment(self, request):
        self.checkMandatoryParams(request, ["role_id"])
        return JsonResponse(mm_Order.proxyBuyCard(request.user.student, int(request.param_dict.get("role_id", 0))))

    @csrf_exempt
    def u_proxy_payment(self, request):
        """
        20年代理商
        """
        if 'detail' not in request.POST:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 detail'})

        purchaseDetail = json.loads(request.POST["detail"])
        if [x for x in ('address', 'phone', 'nickname', 'goods_list', 'price') if x not in purchaseDetail]:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 address, phone, nickname, goods_list, price'})
        openid = request.POST.get('openid')
        client_ip = self.get_client_ip(request)
        return JsonResponse(self.u_proxy_purchase(
            request.user, purchaseDetail, client_ip, openid))

    @csrf_exempt
    def bee_payment(self, request):
        """
        20年小蜜蜂
        """
        if 'detail' not in request.POST:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 detail'})

        purchaseDetail = json.loads(request.POST["detail"])
        if [x for x in ('address', 'phone', 'nickname', 'goods_list', 'price') if x not in purchaseDetail]:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 address, phone, nickname, goods_list, price'})
        openid = request.POST.get('openid')
        client_ip = self.get_client_ip(request)
        return JsonResponse(self.bee_purchase(
            request.user, purchaseDetail, client_ip, openid))

    @csrf_exempt
    def event_payment(self, request):
        if 'detail' not in request.POST:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 detail'})

        if 'user_id' not in request.POST:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 user_id'})

        purchaseDetail = json.loads(request.POST["detail"])
        if [x for x in ('price', 'address', 'phone', 'nickname', 'product_id',
                        'invite_code', 'content', 'items') if x not in purchaseDetail]:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 price, address, phone, nickname, '
                                                      'product_id, invite_code, items '})
        user_id = request.POST['user_id']
        openid = request.POST.get('openid')
        client_ip = self.get_client_ip(request)
        return JsonResponse(self.event_purchase(
            user_id, purchaseDetail, client_ip, openid))

    @csrf_exempt
    def exam_event_payment(self, request):
        if 'detail' not in request.POST:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 detail'})

        if 'user_id' not in request.POST:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 user_id'})

        purchaseDetail = json.loads(request.POST["detail"])
        if [x for x in ('price', 'proxy_id', 'exam_id') if x not in purchaseDetail]:
            return JsonResponse({'retcode': 1, 'msg': '缺少参数 price, proxy_id, exam_id'})
        user_id = request.POST['user_id']
        openid = request.POST.get('openid')
        client_ip = self.get_client_ip(request)
        return JsonResponse(self.exam_event_purchase(
            user_id, purchaseDetail, client_ip, openid))

    @csrf_exempt
    def test_btoc_pay(self, request):

        ret, data = mch_pay(''.join(random.choice(string.ascii_lowercase) for _ in range(5)),
                            "o52cI60iVMQCMqCKAoBCYFZ77PVU", 'NO_CHECK', '', 1, '测试')
        if ret:
            return self.success()
        else:
            return self.error(str(data))


mix_pay_handler = Handler(wechat_logger)
